package com.xyc.petmallsystem.controller;

import com.xyc.petmallsystem.pojo.Coupon;
import com.xyc.petmallsystem.repository.CouponRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Joel
 * @date 2021/11/30
 */

@RestController
@RequestMapping("/coupon")
public class CouponController {

    @Autowired
    CouponRepository couponRepository;

    /*
    添加  uuid优惠码
     */
    @PostMapping("/create")
    public String create() throws ParseException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Coupon coupon2 = new Coupon();
        coupon2.setUuid(UUID.randomUUID().toString().replace("-", ""));
        coupon2.setCreate_time((sdf.parse(sdf.format(date))));
        coupon2.setExpiration_time((sdf.parse(sdf.format(date))));
        coupon2.setState(1);
        Coupon result = couponRepository.save(coupon2);
        System.out.println("生成的兑换码:" + result);
        if (result != null) {
            return result.getUuid();
        } else {
            return "error";
        }
    }

    @GetMapping("/find")
    public List<Coupon> find() {
        return couponRepository.findAll();
    }

    /*
    分页
     */
    @GetMapping("/findPage/{page}/{size}")
    public Page<Coupon> findPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageRequest pageable = PageRequest.of(page - 1, size);
        return couponRepository.findAll(pageable);
    }

    /*
    查询指定id
     */
    @GetMapping("/findById/{id}")
    public Coupon findById(@PathVariable("id") Integer id) {
        System.out.println("要查询的id：" + id); // 输入要查询的id
        return couponRepository.findById(id).get();
    }

    /*
    根据id 删除
     */
    @DeleteMapping("/delById/{id}")
    public void delById(@PathVariable("id") Integer id) {
        System.out.println("删除id:" + id);
        couponRepository.deleteById(id);
    }

    /*
    update  更新
     */
    @PutMapping("/update")
    public String update(@RequestBody Coupon coupon) {

        Coupon result = couponRepository.save(coupon);

        if (result != null) {
            return "success";
        } else {
            return "error";
        }

    }

    /*
    判断优惠码是否存在
     */
    @GetMapping("/judge/{uuid}")
    public String judge(@PathVariable("uuid") String uuid) {
        Coupon result = couponRepository.judge(uuid);
        if (result == null)
            return "error";    //不存在
        Integer state = result.getState();
        if (state == 0) // 存在  已使用
            return "used";
        return "success";// 存在  未使用
    }
}
